package com.wetao.lib_common.utils.uploadfile;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.wetao.lib_common.BuildConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class UploadfileManager {
    private static final OkHttpClient requestClient;
    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())//添加Stetho的拦截器
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new UploadfileManager.LogInterceptor());
        }
        requestClient = builder.build();
    }
    public static OkHttpClient getRequestClient() {
        return requestClient;
    }

    public static class LogInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            ResponseBody responseBody = response.body();
            String content = responseBody.string();
            StringBuilder logBuilder = new StringBuilder();
            logBuilder.append("Request:");
            logBuilder.append("\n\t");
            logBuilder.append(request.url());
            logBuilder.append("\n");
            logBuilder.append("Response:");
            logBuilder.append("\n\t");
            logBuilder.append("code=").append(response.code()).append(",");
            logBuilder.append("message=").append(response.message()).append(",");
            logBuilder.append("\n\t");
            logBuilder.append("body=").append(content);
            return response
                    .newBuilder()
                    .body(ResponseBody.create(responseBody.contentType(), content))
                    .build();
        }
    }
}
